package org.zjvis.datascience.common.widget;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import javafx.util.Pair;
import org.apache.commons.compress.utils.Lists;
import org.zjvis.datascience.common.util.JsonParseUtil;
import org.zjvis.datascience.common.widget.dto.WidgetDTO;
import org.zjvis.datascience.common.widget.enums.RelatedWidgetStatusEnum;
import org.zjvis.datascience.common.widget.request.RelateWidgetResultVO;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @description 可视化图表控件帮助工具类 主要用于处理JSON数据的存取
 * @date 2021-12-08
 */
public class WidgetDTOUtil {

    public static Object getValueByKey(String keyStr, WidgetDTO widget) {
        String[] parts = keyStr.split("\\.");
        Object result = JSONObject.parseObject(widget.getDataJson());
        if (parts.length > 1) {
            for (String key : parts) {
                Pair<String, Object> pair = JsonParseUtil.traverse(key, result);
                result = pair.getValue();
            }
        } else {
            result = ((JSONObject) result).get(parts[0]);
        }
        return result;
    }

    public static Object getValueByKey(String keyStr, JSONObject dataJson) {
        String[] parts = keyStr.split("\\.");
        Object result = dataJson;
        if (parts.length > 1) {
            for (String key : parts) {
                Pair<String, Object> pair = JsonParseUtil.traverse(key, result);
                result = pair.getValue();
            }
        } else {
            result = ((JSONObject) result).get(parts[0]);
        }
        return result;
    }

    public static <T> T getValueByKey(String keyPath, WidgetDTO widget, Class<T> clazz) {
        String[] parts = keyPath.split("\\.");
        Object result = JSONObject.parseObject(widget.getDataJson());
        if (parts.length > 1) {
            for (String key : parts) {
                Pair<String, Object> pair = JsonParseUtil.traverse(key, result);
                result = pair.getValue();
            }
        } else {
            result = ((JSONObject) result).get(parts[0]);
        }
        if (result instanceof JSONObject) {
            return ((JSONObject) result).toJavaObject(clazz);
        } else if (result instanceof JSONArray) {
            return ((JSONArray) result).toJavaObject(clazz);
        }
        return (T) result;
    }

    private static void setValueByKey(Object newValue, String assignedKeyStr, JSONObject dataJson) {
        String[] parts = assignedKeyStr.split("\\.");
        Object result = dataJson;
        if (parts.length > 1) {
            for (int i = 0; i < parts.length; i++) {
                String key = parts[i];
                if (i + 1 == parts.length) {
                    ((JSONObject) result).put(key, newValue);
                } else {
                    Pair<String, Object> pair = JsonParseUtil.traverse(key, result);
                    result = pair.getValue();
                }
            }
        } else {
            ((JSONObject) result).put(assignedKeyStr, newValue);
        }

    }


    /**
     * 用新值 替换 widget - datajson 中的 值
     *
     * @param widget
     * @param key
     * @param updateValue
     */
    public static void updateJsonWithSpecificKey(WidgetDTO widget, String key, Object updateValue) {
        updateJsonWithSpecificKey(widget, key, updateValue, false);
    }

    /**
     * 替换 或者 增量 更新 widget datajson 中的值
     *
     * @param widget
     * @param key
     * @param updateValue
     */
    public static void updateJsonWithSpecificKey(WidgetDTO widget, String key, Object updateValue, Boolean increment) {
        JSONObject widgetDataJson = JSONObject.parseObject(widget.getDataJson());
        if (increment) {

        } else {
            widgetDataJson.put(key, updateValue);
        }
        widget.setDataJson(widgetDataJson.toJSONString());
    }

    public static void updatePublishedJsonWithSpecificKey(WidgetDTO widget, String key, RelateWidgetResultVO updateValue) {
        updatePublishedJsonWithSpecificKey(widget, key, updateValue, false);
    }

    public static void updatePublishedJsonWithSpecificKey(WidgetDTO widget, String key, Object updateValue, Boolean increment) {
        JSONObject widgetPublishedDataJson = JSONObject.parseObject(widget.getPublishDataJson());
        if (increment) {

        } else {
            widgetPublishedDataJson.put(key, updateValue);
        }
        widget.setPublishDataJson(widgetPublishedDataJson.toJSONString());
    }

    public static RelateWidgetResultVO wrapRelatedWidgetResult(WidgetDTO targetWidget, List<WidgetDTO> widgetDTOList, RelatedWidgetStatusEnum statusEnum) {
        RelateWidgetResultVO resultVO = new RelateWidgetResultVO();
        if (ObjectUtil.isNotNull(targetWidget)) {
            resultVO.setWidgetId(targetWidget.getId());
            Pair<String, String> xAttrInfo = targetWidget.getXAttrInfo();
            resultVO.setXAttrStr(xAttrInfo.getKey());
            resultVO.setXAttrValueType(xAttrInfo.getValue());
        }
        if (null != widgetDTOList) {
            resultVO.setRelateWidgets(widgetDTOList.stream().map(item -> {
                return item.toRelatedWidget(statusEnum);
            }).collect(Collectors.toList()));
        } else {
            resultVO.setRelateWidgets(Lists.newArrayList());
        }
        return resultVO;
    }

    public static void main(String[] args) {
        String json = "{\"chartOptions\":{\"title\":\"组件1\",\"titleIsShow\":true,\"xAxisIsShow\":true,\"yAxisIsShow\":true,\"axisGridIsShow\":true,\"xAxisGridIsShow\":true,\"yAxisGridIsShow\":true,\"visibleItemsNumber\":16,\"tooltipIsShow\":true,\"colors\":[\"#5760e6\",\"#FBC94B\",\"#65DCB8\",\"#EF7D52\",\"#F596C6\",\"#687B9D\",\"#5EC6D7\",\"#FFA65E\"],\"xAxisGridStyle\":\"solid\",\"yAxisGridStyle\":\"solid\",\"xAxisTickIsShow\":false,\"yAxisTickIsShow\":false,\"xAxisTitleIsShow\":true,\"xAxisTitle\":\"\",\"yAxisTitleIsShow\":true,\"yAxisTitle\":\"\",\"legendPosition\":\"right\",\"labelIsShow\":false,\"legendIsShow\":true,\"titleTextMaxLength\":30,\"titleFontSize\":16,\"titleFontColor\":\"#373B52\",\"showChart\":false,\"padding\":[10,20,20,10],\"value\":[],\"size\":[400,300],\"dataType\":\"dataset\"},\"widgetJson\":{\"isAggr\":false,\"config\":{\"keys\":[{\"values\":\"\",\"filterType\":\"\",\"sort\":\"asc\"}],\"values\":[{\"sort\":\"\",\"topN\":\"\"}],\"filters\":[]}},\"w\":50,\"chartType\":[\"graph\",\"dagre\"],\"x\":14,\"h\":15,\"y\":0,\"i\":\"dagre26ckewb6\",\"widgetType\":\"system\"}";

        JSONObject jsonObject = JSONObject.parseObject(json);
        Object valueByKey = getValueByKey("setParams[0].formData.cols", jsonObject);
        System.out.println(valueByKey);

    }

}
